package edu.scau.web.pos;

import java.util.Date;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import edu.scau.core.constants.AjaxResult;
import edu.scau.core.constants.HttpStatus;
import edu.scau.pos.service.ProductService;
import edu.scau.pos.vo.ProductVo;
import edu.scau.pos.vo.SaleLineItemVo;
import edu.scau.tool.domain.FileInfo;
import edu.scau.tool.sevice.FileService;
import io.swagger.v3.oas.annotations.Hidden;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Controller
 */
@Tag(name = "商品管理",description = "商品管理接口")
@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;
    @Autowired
    private FileService fileService;

    @Operation(
        summary = "查找所有商品",
        description = "查找所有未删除的商品信息,通过不同商品名分类，展示商品名下所有商品, 访问权限: ALL",
        responses = {
            @ApiResponse(responseCode = "200", description = "成功", content = @Content(mediaType = "application/json", schema = @Schema(implementation = ProductVo.class))),
            @ApiResponse(responseCode = "400", description = "错误", content = @Content(mediaType = "application/json", schema = @Schema(implementation = HttpStatus.class)))
        }
    )
    @Hidden
    @GetMapping("/listAll")
    public AjaxResult listAll() {
        List<Map<String, List<ProductVo>>> productList = productService.listAll();
        return AjaxResult.success(productList);
    }

    @Operation(
            summary = "查找对应分类所有商品/1条",
            description = "查找对应分类未删除的商品信息,通过不同商品名分类，展示商品名下所有商品, 访问权限: ALL",
            responses = {
                    @ApiResponse(responseCode = "200", description = "成功", content = @Content(mediaType = "application/json", schema = @Schema(implementation = ProductVo.class))),
                    @ApiResponse(responseCode = "400", description = "错误", content = @Content(mediaType = "application/json", schema = @Schema(implementation = HttpStatus.class)))
            }
    )
    @GetMapping("/listAllOfOneByCategory")
    public AjaxResult listAllOfOneByCategory(@RequestParam("categoryId") long categoryId) {
        List<Map<String, List<ProductVo>>> productList = productService.listAllOfOneByCategory(categoryId);
        return AjaxResult.success(productList);
    }

    @Operation(
            summary = "查找对应商品名所有商品",
            description = "查找对应商品名所有的商品信息,通过不同商品名分类，展示商品名下所有商品, 访问权限: ALL",
            responses = {
                    @ApiResponse(responseCode = "200", description = "成功", content = @Content(mediaType = "application/json", schema = @Schema(implementation = ProductVo.class))),
                    @ApiResponse(responseCode = "400", description = "错误", content = @Content(mediaType = "application/json", schema = @Schema(implementation = HttpStatus.class)))
            }
    )
    @GetMapping("/listAllOfOneByProductName")
    public AjaxResult listAllOfOneByProductName(@RequestParam("productName") String productName) {
        List<ProductVo> productList = productService.listAllOfOneByProductName(productName);
        return AjaxResult.success(productList);
    }


    @Operation(
            summary = "查找所有商品/1条",
            description = "查找所有未删除的商品信息,通过不同商品名分类，展示商品名下所有商品, 访问权限: ALL",
            responses = {
                    @ApiResponse(responseCode = "200", description = "成功", content = @Content(mediaType = "application/json", schema = @Schema(implementation = ProductVo.class))),
                    @ApiResponse(responseCode = "400", description = "错误", content = @Content(mediaType = "application/json", schema = @Schema(implementation = HttpStatus.class)))
            }
    )
    @GetMapping("/listAllOfOne")
    public AjaxResult listAllOfOne() {
        List<Map<String, List<ProductVo>>> productList = productService.listAllOfOne();
        return AjaxResult.success(productList);
    }

    @Operation(
        summary = "分页查找(以名字分类)",
        description = "分页查找所有未删除的信息, 访问权限: ALL",
        parameters = {
            @Parameter(name = "pageNum", description = "页码", required = true, schema = @Schema(type = "int")),
            @Parameter(name = "pageSize", description = "每页数据条数", required = true, schema = @Schema(type = "int"))
        },
        responses = {
            @ApiResponse(responseCode = "200", description = "成功", content = @Content(mediaType = "application/json", schema = @Schema(implementation = ProductVo.class))), // 返回 PageInfo 对象
            @ApiResponse(responseCode = "500", description = "错误", content = @Content(mediaType = "application/json", schema = @Schema(implementation = HttpStatus.class))) // 返回 AjaxResult 对象
        }
    )
    @GetMapping("/listByPage")
    public AjaxResult listByPage(
        @RequestParam("pageNum") Integer pageNum,
        @RequestParam("pageSize") Integer pageSize
    ) {
        PageHelper.startPage(pageNum, pageSize);
        List<Map<String, List<ProductVo>>> productList = productService.listAll();
        PageInfo<Map<String, List<ProductVo>>> pageInfo = new PageInfo<>(productList);
        return AjaxResult.success(pageInfo);
    }

    @Operation(
        summary = "根据SN查找商品",
        description = "根SN查找信息, 访问权限:ALL",
        parameters = {
            @Parameter(name = "productSn", description = "productSn", required = true, schema = @Schema(type = "String"))
        },
        responses = {
            @ApiResponse(responseCode = "200", description = "成功", content = @Content(mediaType = "application/json", schema = @Schema(implementation =
                    ProductVo.class))),
            @ApiResponse(responseCode = "204", description = "不存在", content = @Content(mediaType = "application/json", schema = @Schema(implementation = HttpStatus.class)))
        }
    )
    @GetMapping("/findProductBySn")
    public AjaxResult findProductBySn(@RequestParam("productSn") String productSn) {
        ProductVo product = productService.findProductBySn(productSn);
        if (product != null) {
            return AjaxResult.success(product);
        } else {
            return AjaxResult.success("商品不存在！", HttpStatus.NO_CONTENT);
        }
    }

    @Operation(
        summary = "更新商品信息",
        description = "根据SN更新信息, SN必需字段, 访问权限:admin、cashier",
        requestBody = @RequestBody(
            description = "更新条件,SN是必须的",
            required = true,
            content = @Content(
                mediaType = "application/json",
                schema = @Schema(implementation = ProductVo.class)
            )
        ),
        responses = {
            @ApiResponse(responseCode = "200", description = "成功", content = @Content(mediaType = "application/json", schema = @Schema(implementation = HttpStatus.class))),
            @ApiResponse(responseCode = "500", description = "更新失败", content = @Content(mediaType = "application/json", schema = @Schema(implementation = HttpStatus.class)))
        }
    )
    @PutMapping("/update")
    @PreAuthorize("hasAnyAuthority('admin','cashier')")
    public AjaxResult updateProduct(@Validated @org.springframework.web.bind.annotation.RequestBody ProductVo productVo) {
        try {
            int res = productService.updateProduct(productVo);
            return res > 0 ? AjaxResult.success(HttpStatus.SUCCESS) : AjaxResult.error("更新失败");
        }
        catch (IllegalArgumentException e){
            return AjaxResult.error(HttpStatus.BAD_REQUEST,e.getMessage());
        }
    }

    @Operation(
        summary = "插入商品信息",
        description = "插入信息信息, 访问权限admin、cashier",
        requestBody = @RequestBody(
            description = "插入条件",
            required = true,
            content = @Content(
                mediaType = "application/json",
                schema = @Schema(implementation = ProductVo.class)
            )
        ),
        responses = {
            @ApiResponse(responseCode = "200", description = "成功", content = @Content(mediaType = "application/json", schema = @Schema(implementation = HttpStatus.class))),
            @ApiResponse(responseCode = "500", description = "插入失败", content = @Content(mediaType = "application/json", schema = @Schema(implementation = HttpStatus.class)))
        }
    )
    @PutMapping("/insert")
    @Hidden
    @PreAuthorize("hasAnyAuthority('admin','cashier')")
    public AjaxResult insertProduct(@org.springframework.web.bind.annotation.RequestBody ProductVo productVo) {
       try {
           int res = productService.insertProduct(productVo);
           return res > 0 ? AjaxResult.success(200) : AjaxResult.error("插入失败！");
       }
       catch (IllegalArgumentException e){
           return AjaxResult.error(HttpStatus.BAD_REQUEST,e.getMessage());
       }
    }

    @Operation(
            summary = "上传图片",
            description = "上传图片接口",
            responses = {
                    @ApiResponse( description = "url:上传的图片地址", content = @Content(mediaType = "application/json", schema = @Schema(implementation = HttpStatus.class)))
            }
    )
    @PostMapping("upload")
    public AjaxResult uploadFile(@RequestParam(value = "file") MultipartFile file)  {
        String url = productService.uploadFile(file);
        Map data = new HashMap<String, Object>();
        data.put("url", url);
        return AjaxResult.success(data);
    }

    @Operation(
            summary = "插入商品和库存",
            description = "插入信息信息,同时设置对应库存数据,颜色和尺寸的设置严格遵循约定文档, 访问权限admin、cashier",
            requestBody = @RequestBody(
                    description = "插入条件",
                    required = true,
                    content = @Content(
                            mediaType = "application/json",
                            schema = @Schema(implementation = ProductVo.class)
                    )
            ),
            responses = {
                    @ApiResponse(responseCode = "200", description = "成功", content = @Content(mediaType = "application/json", schema = @Schema(implementation = HttpStatus.class))),
                    @ApiResponse(responseCode = "500", description = "插入失败", content = @Content(mediaType = "application/json", schema = @Schema(implementation = HttpStatus.class)))
            }
    )
    @PutMapping("/insertProduct")
    @PreAuthorize("hasAnyAuthority('admin','cashier')")
    public AjaxResult insertProductAndSku(@Validated  @org.springframework.web.bind.annotation.RequestBody ProductVo productVo) {
        try {
            int res = productService.insertProductAndSku(productVo);
            return res > 0 ? AjaxResult.success(200) : AjaxResult.error("插入失败！");
        }
        catch (IllegalArgumentException e){
            return AjaxResult.error(HttpStatus.BAD_REQUEST,e.getMessage());
        }
    }

    @Operation(
        summary = "根据Sn删除商品",
        description = "根据Sn删除商品信息,访问权限:admin、cashier",
        parameters = {
            @Parameter(name = "productSn", description = "productSn", required = true, schema = @Schema(type = "String"))
        },
        responses = {
            @ApiResponse(responseCode = "200", description = "成功", content = @Content(mediaType = "application/json", schema = @Schema(implementation = HttpStatus.class))),
            @ApiResponse(responseCode = "500", description = "删除失败", content = @Content(mediaType = "application/json", schema = @Schema(implementation = HttpStatus.class)))
        }
    )
    @DeleteMapping("/delete")
    @PreAuthorize("hasAnyAuthority('admin','cashier')")
    public AjaxResult delete(@RequestParam("productSn") String productSn) {
        int res = productService.deleteProductBySn(productSn);
        return res > 0 ? AjaxResult.success("删除成功", 200) : AjaxResult.error("删除失败");
    }
    @Operation(
            summary = "批量更新商品库存",
            parameters = {
                    @Parameter(
                            name = "saleLineItemVoList",
                            description = "销售商品条目列表",
                            required = true,
                            schema = @Schema(
                                    type = "array",  // 指定为数组类型
                                    implementation = SaleLineItemVo.class  // 指定数组元素类型
                            )
                    )
            }
    )
    @PostMapping("/batchUpdateStock")
    @PreAuthorize("hasAnyAuthority('admin','cashier')")
    public AjaxResult batchUpdateStock(@org.springframework.web.bind.annotation.RequestBody List<SaleLineItemVo> saleLineItemVoList){
        return AjaxResult.success(productService.batchUpdateStock(saleLineItemVoList));
    }

    @Operation(
            summary = "根据分类查找对应商品",
            description = "根据分类查找对应商品",
            responses = {
                    @ApiResponse(responseCode = "200", description = "成功", content = @Content(mediaType = "application/json", schema = @Schema(implementation =
                            ProductVo.class))),
                    @ApiResponse(responseCode = "204", description = "不存在", content = @Content(mediaType = "application/json", schema = @Schema(implementation = HttpStatus.class)))
            }
    )
    @GetMapping("/getProductOfCategory")
    public AjaxResult getProductOfCategory(@RequestParam("categoryId") long categoryId) {
        List<Map<String, List<ProductVo>>> productList=productService.getProductOfCategory(categoryId);
        return AjaxResult.success(productList);
    }

    @Operation(
            summary = "分页查找商品(后台)",
            description = "分页查找商品(后台),和数据库数据结果一致",
            responses = {
                    @ApiResponse(responseCode = "204", description = "不存在", content = @Content(mediaType = "application/json", schema = @Schema(implementation = ProductVo.class)))
            }
    )
    @GetMapping("/listProductOfDb")
    public AjaxResult listProductOfDb(
            @RequestParam("pageNum") Integer pageNum,
            @RequestParam("pageSize") Integer pageSize
    ) {
        PageHelper.startPage(pageNum, pageSize);
        List<ProductVo> productList = productService.listAllOfDb();
        PageInfo<ProductVo> pageInfo = new PageInfo<>(productList);
        return AjaxResult.success(pageInfo);
    }



}
